package com.huisenky.smallidea.buddy;

import cn.hutool.core.util.ReflectUtil;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/*
    生成的.class文件在 target中  classes下
 */
public class UserMain {
    public static void main(String[] args) throws IOException {
        Map<String, Class<?>> dict = new LinkedHashMap<>();
        Field[] userFields = ReflectUtil.getFields(User.class);
        for (Field userField : userFields) {
            dict.put(userField.getName(), userField.getType());
        }
        Field[] userVOFields = ReflectUtil.getFields(UserVO.class);
        for (Field userVOField : userVOFields) {
            dict.put(userVOField.getName(), userVOField.getType());
        }
//      DynamicType.Builder<Object> proxyBuilder = new ByteBuddy().subclass(Object.class).name("UserVO$Proxy").annotateType(AnnotationDescription.Builder.ofType(ApiModel.class).build());
        DynamicType.Builder<Object> proxyBuilder = new ByteBuddy().subclass(Object.class).name("UserVO$Proxy");
        for (Map.Entry<String, Class<?>> entry : dict.entrySet()) {
            proxyBuilder = proxyBuilder.defineProperty(entry.getKey(), entry.getValue());
        }
        Class<?> loaded = proxyBuilder.make().load(Thread.currentThread().getContextClassLoader()).getLoaded();
        proxyBuilder.make().saveIn(new File(UserMain.class.getResource("/").getPath()));

        //获取到 class 并且赋值
        Field[] newfields = ReflectUtil.getFields("UserVO$Proxy".getClass());
        for (Field field:
        newfields) {

        }
        try {
            Class<?> userVO$Proxy = Class.forName("UserVO$Proxy");
            Object o = null;
            try {
                o = userVO$Proxy.newInstance();
                ReflectUtil.setFieldValue(o,"name","张三");
                Object name = ReflectUtil.getFieldValue(o, "name");
                System.out.println(name);
                System.out.println(o.toString());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}
